# This is a sample Python script.
# python 3.9
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# https://developer.nvidia.com/cuda-downloads  最新版本
# https://developer.nvidia.com/cuda-11-7-0-download-archive?target_os=Windows&target_arch=x86_64
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple flask easyocr
#  pip install -U sympy==1.13.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install torch==2.0.1+cu117 torchvision==0.15.2+cu117 -f https://download.pytorch.org/whl/torch_stable.html
# pip install -U numpy==1.26.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
import base64
import json
import threading

from PIL import Image
from flask import Flask
from flask import request
import os
import easyocr
import torch
from io import BytesIO

import io
import time
from config import DICT, SAVE_JSON
print(torch.__version__)
print(torch.cuda.is_available())
r = easyocr.Reader(['ch_sim', "en"], gpu=True)

app = Flask(__name__)
app.json.ensure_ascii = False

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# 10.10.127.36 10.10.127.34 255.255.255.0 10.10.127.34 144.144.144.144 默认模式
# 需要easyocr , flask
# https://www.bilibili.com/read/cv33816639/
#   http://10.10.127.34:5000/api/python/getText
#  http://10.10.127.34:5000/api/python/getJson
# adb connect 127.0.0.1:16384
dist = DICT
json_project_home = dist+"\BaiduSyncdisk\游戏攻略\异世界勇者脚本"
json_path_my = dist+"\BaiduSyncdisk\游戏攻略\异世界勇者脚本\config.json"
json_path_my_1920 = dist+"\BaiduSyncdisk\游戏攻略\异世界勇者脚本\config_1920.json"
output_img = dist+"/out.png"

@app.route('/api/python/getText')
def get_text():
    p = request.args.get("path")
    res = r.readtext(p, detail=0)

    return res


@app.route('/api/python/getJson')
def get_text_json():
    with open(json_path_my, "r", encoding='utf-8') as f:
        text_data = f.read()
        json_data = json.loads(text_data)
        # print(json_data)
        return json_data


def find_file_json():
    if os.path.exists(SAVE_JSON):
        json_data = None
        with open(SAVE_JSON, "r", encoding='utf-8') as f:
            text_data = f.read()
            json_data = json.loads(text_data)
            print(json_data)
            if json_data["data"] == -1 or json_data["data"] is None:
                time.sleep(0.05)
                return find_file_json()
        with open(SAVE_JSON, "w", encoding='utf-8') as f:
            f.write("{\"data\": -1}")
        return json_data
    else:
        time.sleep(0.05)
        return find_file_json()


@app.route('/api/python/getJsonByFile')
def get_text_json_by_file():
    return find_file_json()


@app.route('/api/python/getJson1920')
def get_text_json1920():
    with open(json_path_my_1920, "r", encoding='utf-8') as f:
        text_data = f.read()
        json_data = json.loads(text_data)
        # print(json_data)
        return json_data


@app.route('/api/python/getJsonAny')
def get_text_json_any():
    # name = a.json
    p = str(request.args.get("name"))
    with open(json_project_home + "\\" + bytes.fromhex(p).decode("utf-8"), "r", encoding='utf-8') as f:
        text_data = f.read()
        json_data = json.loads(text_data)
        # print(json_data)
        return json_data


def get_value_by_path(data, path):
    # 将路径分割成单个键
    keys = path.split('-')
    # 递归查找值
    for key in keys:
        data = data.get(key)
        if data is None:
            return None
    return data


def rgb_to_hex(rgb):
    return '#{:02x}{:02x}{:02x}'.format(rgb[2], rgb[1], rgb[0])


@app.route('/api/python/printJson', methods=['POST'])
def get_print_json():
    pb = request.form.get("json")
    a = json.loads(pb)
    print(json.dumps(a,indent=4,sort_keys=True, ensure_ascii=False))
    # name = a.json
    return {"msg":"成功"}

def img2byte(img):
    img_b = io.BytesIO()
    img.save(img_b,format="PNG")
    return img_b.getvalue()


@app.route('/api/python/post_file', methods=['POST'])
def post_file():
    uploaded_file = request.files['file']  # 获取上传的文件
    if uploaded_file:
        uploaded_file.save("output.png")
        res1 = r.readtext("output.png", detail=0)
        print(res1)
        j = json.dumps({"data": res1}, ensure_ascii=False)
        return j
    else:
        return {"msg":"失败"}


@app.route('/api/python/saveJson', methods=['POST'])
def w():
    pb = request.form.get("json")
    # name = a.json
    name = request.form.get("name")
    path = json_project_home + "\\" + bytes.fromhex(name).decode("utf-8")
    with open(path, "w", encoding='utf-8') as f:
        f.write(pb)


@app.route('/api/python/imgColor', methods=['POST'])
def get_img_color():
    pb = request.form.get("picBase")
    json_p = request.form.get("j")
    pb = pb.replace("_JH_", "+")

    print("已经接受到数据！")
    imag_data = base64.b64decode(pb)
    image = Image.open(BytesIO(imag_data))

    # 保存图片到文件
    image.save(output_img, 'PNG')
    img = Image.open(output_img)
    # img.getpixel((x, y))
    with open(json_path_my, "r", encoding='utf-8') as f:
        text_data = f.read()
        json_data = json.loads(text_data)
        line_center = json_data["lineCenter"]
        row_center = line_center["row"]
        col_center = line_center["col"]
        # print(json_data)
        jd = get_value_by_path(json_data, json_p)  # 数组
        if jd is not None:
            for i in jd:
                row = i["row"]
                col = i["col"]
                # 计算位置 x,y
                r1 = col_center[row - 1]
                c1 = row_center[col - 1]
                x = c1 - 8
                y = r1 - 40
                if "burial" in i and i["burial"] is False:
                    pass
                else:
                    i["x"] = x
                    i["y"] = y

                    cc1 = img.getpixel((x, y))
                    cc2 = rgb_to_hex(cc1).upper()
                    i["color"] = cc2.replace("#", "")

        json_string = json.dumps(jd)
        print(json_string)
        return "成功"


@app.route('/api/python/getJsonStr', methods=['POST'])
def get_text_post_json_str():
    pb = request.form.get("js")
    print(pb)
    return "成功"


@app.route('/api/python/getTextPost', methods=['POST'])
def get_text_post():
    # data = request.get_json()  # 获取JSON格式的POST数据
    # pb = request.args.get("picBase")
    # key1 = data.get('picBase')
    pb = request.form.get("picBase")
    pb = pb.replace(" ", "+")

    imag_data = base64.b64decode(pb)
    #     res = r.readtext(p, detail= 0)
    res = r.readtext(imag_data, detail=0)
    print(res)
    return json.dumps({"data": res}, ensure_ascii=False)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
